<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Validate;

class Api extends Controller
{
    /**
     * 短信发送
     * */
    public function sendSms()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];

        if (empty($mobile)) return apiReturn(2, '请输入手机号码');

        //获取手机号
        $pattern = "/^1[0123456789]\d{9}$/";
        if (empty($mobile)) {
            return apiReturn(2, '请输入手机号');
        } else {
            if (preg_match($pattern, $mobile)) {
                //判断当前手机有没有发送过验证码
                $result = Db::name('sms_code')->where(['mobile' => $mobile])->order('create_time desc')->find();
                $result = time() - $result['create_time'];
                if ($result < 60 and $result > 0) {
                    return apiReturn(2, '当前手机号操作频繁,请稍后再试');
                }
                $authnum = rand(100000, 999999);
                $statusStr = [
                    "0" => 1,
                    "-1" => "参数不全",
                    "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                    "30" => "密码错误",
                    "40" => "账号不存在",
                    "41" => "余额不足",
                    "42" => "帐户已过期",
                    "43" => "IP地址限制",
                    "50" => "内容含有敏感词"
                ];
                $smsapi = "http://api.smsbao.com/";
                $user = 'xvzhou';         //短信平台帐号
                $pass = md5('8691xzadz'); //短信平台密码
                $content = '【特汇鲜品】您的验证码是' . $authnum . '。如非本人操作，请忽略本短信';
                $phone = $mobile;//要发送短信的手机号码
                $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
                $result = file_get_contents($sendurl);
                if ($result == 0) {
                    $info['code'] = $authnum;
                    $info['mobile'] = $phone;
                    $info['create_time'] = time();
                    $info['failure_time'] = time() + 600;//失效时间：10分钟
                    Db::name('sms_code')->insert($info);
                    return apiReturn(1, '短信发送成功');
                } else {
                    return apiReturn(2, $statusStr[$result]);
                }
            } else {
                return apiReturn(2, '手机号码格式错误');
            }
        }
    }

    /**
     * 手机号验证码登录
     * */
    public function mobileCodeLogin()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $code = $input['code'];

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (empty($code)) apiReturn(2, '请输入验证码');


        $info = Db::name('sms_code')->where(['mobile' => $mobile, 'code' => $code])->find();
        if (empty($info)) apiReturn(2, '验证码错误');
        if (time() > $info['failure_time']) apiReturn(2, '验证码已失效');

        $info = Db::name('user')->where(['mobile' => $mobile])->find();
        if ($info['status'] == 2) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (!$info) {
            // 新用户
            $save_data = [
                'username' => '微信用户',
                'mobile' => $mobile,
                'code' => createCode(),
                'create_time' => time()
            ];

            $id = Db::name('user')->insertGetId($save_data);
        } else {
            $id = $info['id'];
        }

        $qr = $info['qr'];

        if ($id) {
            apiReturn(1, '登录成功', $id);
        } else {
            apiReturn(2, '登录失败');
        }
    }

    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(file_get_contents($url));

        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~');

        $openid = $user_data->openid;
        if ($openid) $user_id = Db::name('user')->where('openid', $openid)->value('id');

        $data = [
            'openid' => $openid,
            'user_id' => $user_id ? : 0
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 用户登录
     * */
    public function login()
    {
        $input = Request()->param();

        $openid = $input['openid'];
        $username = $input['username'];
        $avatar = $input['avatar'] ? : 0;
        $mobile = $input['mobile'];

        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($username)) apiReturn(2, '昵称缺失');
        if (empty($mobile)) apiReturn(2, '请获取手机号');

        $info = Db::name('user')->where(['openid' => $openid])->find();
        if ($info) {
            if ($info['status'] == 2) apiReturn(2, '用户已被禁用');

            apiReturn(1, '登录成功', $info['id']);
        } else {
            // 注册新用户
            $data = [
                'openid' => $openid,
                'username' => $username,
                'avatar' => $avatar,
                'mobile' => $mobile,
                'create_time' => time()
            ];

            $id = Db::name('user')->insertGetId($data);

            apiReturn(1, '登录成功', $id);
        }
    }

    /**
     * 省市区地址获取
     * */
    public function getRegion()
    {
        $province_list = Db::name('province')->field('province_id value,name label')->order('province_id asc')->select();
        foreach ($province_list as &$v) {
            $city_list = Db::name('city')->field('city_id value,name label')->where(['province_id' => $v['value']])->order('city_id asc')->select();

            foreach ($city_list as &$val) {
                $area_list = Db::name('area')->field('area_id value,name label')->where(['city_id' => $val['value']])->order('area_id asc')->select();
                $val['children'] = $area_list;
            }

            $v['children'] = $city_list;
        }

        apiReturn(1, '获取数据成功', $province_list);
    }

    /**
     * 认养协议
     * */
    public function getMealArticle()
    {
        $content = Db::name('meal_article')->value('content');

        apiReturn(1, '获取数据成功', doEditorContent($content));
    }

    /**
     * 获取最近门店
     * */
    public function getShop()
    {
        $input = Request()->param();

        $lat = $input['lat'];
        $lng = $input['lng'];

        if (empty($lat) || empty($lng)) apiReturn(2, '定位信息缺失');

        $sql = "SELECT *,(st_distance(point(lng,lat),point(${lng},${lat}))*111195/1000 ) as juli FROM cater_shop ORDER BY juli ASC";
        $list = Db::query($sql);

        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 微信登录
     * */
    public function wxLogin()
    {
        $input = Request()->param();

        $code = $input['code'];
        $nickname = $input['nickname'] ? : '微信用户';
        $avatar = $input['avatar'] ? : 0;

        if (empty($code)) apiReturn(2, 'CODE缺失');
        if (empty($nickname)) apiReturn(2, '用户昵称缺失');
        //        if (empty($avatar)) apiReturn(2, '头像缺失');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $user_data = json_decode(file_get_contents($url));

        $openid = $user_data->openid;

        if (empty($openid)) apiReturn(2, 'openid获取失败');

        $info = Db::name('user')->where(['openid' => $openid])->find();
        if ($info['status'] == 2) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (!$info) {
            // 新用户
            $save_data = [
                'username' => $nickname,
                'avatar' => $avatar,
                'openid' => $openid,
                'create_time' => time()
            ];

            $id = Db::name('user')->insertGetId($save_data);
        } else {
            // 老用户
            $id = $info['id'];
        }

        if ($id) {

            $mobile = Db::name('user')->where(['id' => $id])->value('mobile');

            $data = [
                'user_id' => $id,
                'mobile' => $mobile ? : ''
            ];

            apiReturn(1, '登录成功', $data);
        } else {
            apiReturn(2, '登录失败');
        }
    }

    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

        $token = getAccessToken();
        if (empty($token)) apiReturn(2, 'TOKEN缺失');

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        $result = json_decode($result, true);

        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];

            if ($mobile) {
                apiReturn(1, '获取数据成功', $mobile);
            } else {
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            if ($result['errcode'] == 40001) {
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }

    /**
     * 首页banner
     * */
    public function indexBanner()
    {
        $input = Request()->param();

        $shop_id = $input['shop_id'];

        if (empty($shop_id)) apiReturn(2, '门店ID缺失');

        $banner_list = Db::name('banner')->field('id,img,type,to_id')->where(['shop_id' => $shop_id])->order('id desc')->select();

        if ($banner_list) {
            foreach ($banner_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $banner_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * banner文章详情
     * */
    public function bannerArticleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '文章ID缺失');

        $info = Db::name('article')->field('id,title,content,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在或已删除');
        }
    }

    /**
     * 商品分类
     * */
    public function goodsTypeList()
    {
        $input = Request()->param();

        $shop_id = $input['shop_id'];

        if (empty($shop_id)) apiReturn(2, '门店ID缺失');

        $list = Db::name('goods_type')->field('id,name,img')->where(['shop_id' => $shop_id])->order('sort asc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 商品品牌
     * */
    public function goodsBrandList()
    {
        $list = Db::name('goods_brand')->field('id,name')->order('sort asc')->select();

        if ($list) {
            apiReturn(1, '获取数据成', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 获取店铺满多少元配送
     * */
    public function getShopFullPriceSend()
    {
        $input = Request()->param();

        $shop_id = $input['shop_id'];

        $full_price_send = Db::name('shop')->where(['id' => $shop_id])->value('full_price_send');

        apiReturn(1, '获取数据成功', $full_price_send ? sprintf('%.2f', $full_price_send) : 0);
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $name = $input['name'];
        $shop_id = $input['shop_id'];
        $one_type_id = $input['one_type_id'] ? : 0;
        $is_recommend = $input['is_recommend'] ? : 0;
        $sort = $input['sort'] ? : 0;//1：综合排序，2：销量排序，3：价格排序
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($shop_id)) apiReturn(2, '门店ID缺失');

        $where['upper'] = 1;
        $where['shop_id'] = $shop_id;

        if ($name) $where['name'] = ['LIKE', '%' . $name . '%'];
        if ($is_recommend) $where['is_recommend'] = $is_recommend;
        if ($one_type_id) $where['one_type_id'] = $one_type_id;

        if ($sort == 2) {
            $order = 'sales_count desc';
        } else if ($sort == 3) {
            $order = 'min_price asc';
        } else {
            $order = 'create_time desc';
        }

        $goods_list = Db::name('goods')->field('id,img,name,min_price,sales_count')->where($where)->order($order)->page($page, $pagesize)->select();
        if ($goods_list) {
            foreach ($goods_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $goods_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 检查商品库存
     * @param $goods_id  int 商品id
     * @param $buy_count int 购买数量
     * @return bool
     * */
    public function checkStock($goods_id, $buy_count)
    {
        if ($goods_id && $buy_count) {
            $stock_count = Db::name('goods')->where(['id' => $goods_id])->value('stock_count');

            if ($stock_count >= $buy_count) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 检查商品库存
     * */
    public function checkGoodsStock()
    {
        $input = Request()->param();

        $car_ids = $input['car_ids'] ? : '';
        $goods_id = $input['goods_id'] ? : 0;
        $buy_count = $input['buy_count'] ? : 0;


        if (empty($car_ids)) {
            if (empty($goods_id)) apiReturn(2, '商品ID缺失');
            if (empty($buy_count)) apiReturn(2, '购买数量缺失');
        }
        if (empty($car_ids) && empty($goods_id) && empty($buy_count)) apiReturn(2, '参数缺失');

        if ($car_ids) {
            // 购物车下单检查商品库存是否充足
            $car_list = Db::name('goods_car')
                ->field('goods_id, SUM(count) as count')
                ->where(['id' => ['IN', $car_ids]])
                ->group('goods_id')
                ->select();

            // 哪些商品库存不足记录下来
            $goods_name_arr = [];
            foreach ($car_list as &$v) {
                $check = $this->checkStock($v['goods_id'], $v['count']);
                if (!$check) $goods_name_arr[] = getGoodsName($v['goods_id']);
            }

            if (empty($goods_name_arr)) {
                apiReturn(1, '库存充足');
            } else {
                apiReturn(3, implode('，', $goods_name_arr) . '库存不足，请修改购买数量后重新下单');
            }
        } else {
            // 商品详情下单检查商品库存是否充足
            $check = $this->checkStock($goods_id, $buy_count);
            if ($check) {
                apiReturn(1, '库存充足');
            } else {
                apiReturn(3, getGoodsName($goods_id) . '库存不足，请修改购买数量后重新下单');
            }
        }
    }

    /**
     * 商品详情
     * */
    public function goodsDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '商品ID缺失');

        $info = Db::name('goods')->field('id,name,img,imgs,limit_buy_count,stock_count,sales_count,min_price,content')->where(['id' => $id])->find();
        if ($info) {
            $info['img'] = getPicture($info['img']);
            $info['imgs'] = doImgs($info['imgs']);
            $min_market_price = Db::name('sku_value')->where(['goods_id' => $id, 'status' => 1])->min('market_price');
            $info['min_market_price'] = sprintf('%.2f', $min_market_price);
            $info['content'] = doEditorContent($info['content']);

            $sku_data = getSku($id);

            $info['sku_list'] = $sku_data['sku_list'];
            $info['sku_value_list'] = $sku_data['sku_value_list'];

            $comment_count = Db::name('goods_comment')->where(['goods_id' => $id])->count();
            $info['comment_count'] = $comment_count;

            $format_price = formatPrice($info['min_price']);
            $info['integer_price'] = $format_price['integer'];
            $info['decimal_price'] = $format_price['decimal'];

            //评价列表
            $comment_list = Db::name('goods_comment c')
                ->join('cater_user u', 'c.user_id = u.id', 'left')
                ->field('c.id,u.avatar,u.username,c.star,c.content,c.imgs,c.create_time')
                ->where(['c.goods_id' => $id])
                ->order('c.create_time desc')
                ->limit(2)
                ->select();
            if ($comment_list) {
                foreach ($comment_list as &$v) {
                    $v['avatar'] = doAvatar($v['avatar']);
                    $v['imgs'] = doImgs($v['imgs']);
                    $v['star'] = intval($v['star']);
                    $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
                }
            } else {
                $comment_list = [];
            }
            $info['comment_list'] = $comment_list;

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }

    /**
     * 核销自提订单
     * */
    public function verifyOrder()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $order_info = Db::name('order')->where(['id' => $id])->find();
        if ($order_info) {
            $shop_id = $order_info['shop_id'];

            $shop_list = Db::name('shop')->where("find_in_set(${user_id}, user_ids)")->select();
            if ($shop_list) {
                $shop_ids = array_column($shop_list, 'id');
                if (in_array($shop_id, $shop_ids)) {
                    $res = Db::name('order')->where(['id' => $id])->setField('status', 4);
                    if ($res) {
                        apiReturn(1, '核销成功');
                    } else {
                        apiReturn(2, '核销失败或已核销');
                    }
                } else {
                    apiReturn(2, '您暂无该门店核销权限');
                }
            } else {
                apiReturn(2, '您暂无该门店核销权限');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 套餐列表
     * */
    public function mealList()
    {
        $input = Request()->param();

        $name = $input['name'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['upper'] = 1;
        if ($name) $where['name'] = ['like', '%' . $name . '%'];

        $list = Db::name('meal')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 套餐详情
     * */
    public function mealDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '套餐ID缺失');

        $info = Db::name('meal')->where(['id' => $id])->find();
        if ($info) {
            $info['imgs'] = doImgs($info['imgs']);
            $info['content'] = doEditorContent($info['content']);

            $info['meal_buy_notice'] = C('MEAL_BUY_NOTICE');

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '套餐不存在或已删除');
        }
    }

    /**
     * 收藏/取消收藏
     * */
    public function doCollect()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $to_id = $input['to_id'];
        $type = $input['type'];    //1：商品
        $status = $input['status'];//0：取消收藏，1：收藏

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($to_id)) apiReturn(2, '收藏对象ID缺失');

        $time = time();

        $info = Db::name('collect')->where(['user_id' => $user_id, 'to_id' => $to_id, 'type' => $type])->find();
        if ($info) {
            if ($info['status'] == $status) {
                apiReturn(2, '系统繁忙，请稍后再试~');
            } else {
                $data = [
                    'status' => $status,
                    'update_time' => $time,
                    'create_time' => $time
                ];
                $res = Db::name('collect')->where(['id' => $info['id']])->update($data);
                $msg = $status == 0 ? '取消收藏' : '收藏';
                if ($res) {
                    apiReturn(1, $msg . '成功');
                } else {
                    apiReturn(2, $msg . '失败');
                }
            }
        } else {
            if ($status == 0) {
                apiReturn(2, '系统繁忙，请稍后再试~');
            } else {
                $data = [
                    'user_id' => $user_id,
                    'to_id' => $to_id,
                    'type' => $type,
                    'status' => $status,
                    'create_time' => $time
                ];
                $res = Db::name('collect')->insert($data);
                if ($res) {
                    apiReturn(1, '收藏成功');
                } else {
                    apiReturn(2, '收藏失败');
                }
            }
        }
    }

    /**
     * 商品评价列表
     * */
    public function goodsCommentList()
    {
        $input = Request()->param();

        $id = $input['id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($id)) apiReturn(2, '商品ID缺失');

        $list = Db::name('goods_comment c')
            ->join('cater_user u', 'c.user_id = u.id', 'left')
            ->field('c.id,u.avatar,u.username,c.star,c.content,c.imgs,c.create_time')
            ->where(['c.goods_id' => $id])
            ->order('c.create_time desc')
            ->page($page, $pagesize)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = doAvatar($v['avatar']);
                $v['imgs'] = doImgs($v['imgs']);
                $v['star'] = intval($v['star']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 购物车商品数量校正
     * tips：在小程序 onHide 和 onUnload 中调用该接口
     * */
    public function doCarGoodsCount()
    {
        $input = Request()->param();

        $car_list = json_decode($input['car_list'], true);//[{"id":"4","count":"8"}]

        if ($car_list) {
            foreach ($car_list as &$v) {
                Db::name('goods_car')->where(['id' => $v['id']])->setField('count', $v['count']);
            }
        }
    }

    /**
     * 加入购物车
     * */
    public function addGoodsCar()
    {
        $input = Request()->param();

        $id = $input['id'];//商品id
        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $sku_id = $input['sku_id'];//属性id组合；sku_value表sku_id
        $count = $input['count'];

        if (empty($id)) apiReturn(2, '商品ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if ($count <= 0) apiReturn(2, '商品数量异常');

        $goods_info = Db::name('goods')->where(['id' => $id])->find();
        if ($goods_info) {
            $goods_car_count = Db::name('goods_car')->where(['user_id' => $user_id, 'goods_id' => $id])->value('count');
            if ($goods_info['limit_buy_count'] > 0 && $goods_car_count + $count > $goods_info['limit_buy_count']) apiReturn(2, '超出商品限购数量');

            $sku_info = Db::name('sku_value')->field('sku_id,img,price,stock')->where(['sku_id' => $sku_id, 'goods_id' => $id])->find();
            if ($sku_info) {
                //                if ($sku_info['stock'] < $count) apiReturn(2, '商品所选属性库存不足');

                $car_info = Db::name('goods_car')->where(['user_id' => $user_id, 'goods_id' => $id, 'sku_id' => $sku_id])->find();
                if ($car_info) {
                    //该商品之前已经加入过购物车，这个时候只需要增加购物车数量即可
                    $res = Db::name('goods_car')->where(['id' => $car_info['id']])->setInc('count', $count);
                } else {
                    //该商品第一次加入购物车，添加购物车数据
                    $data = [
                        'user_id' => $user_id,
                        'goods_id' => $id,
                        'shop_id' => $goods_info['shop_id'],
                        'img' => $sku_info['img'],
                        'sku_id' => $sku_info['sku_id'],
                        'count' => $count,
                        'price' => $sku_info['price'],
                        'create_time' => time()
                    ];
                    $res = Db::name('goods_car')->insert($data);
                }
            } else {
                apiReturn(2, '属性不存在或已删除');
            }

            if ($res) {
                $shop_id = Db::name('goods')->where(['id' => $id])->value('shop_id');
                $count = Db::name('goods_car')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->count();

                apiReturn(1, '添加成功', $count ? : 0);
            } else {
                apiReturn(2, '添加购物车失败');
            }
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }

    public function goodsCarCount()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $shop_id = $input['shop_id'];

        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($shop_id)) apiReturn(2, '门店ID缺失');

        $count = Db::name('goods_car')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->count();

        apiReturn(1, '获取数据成功', $count ? : 0);
    }

    /**
     * 购物车列表
     * */
    public function goodsCarList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $shop_id = $input['shop_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($shop_id)) apiReturn(2, '门店ID缺失');


        $list = Db::name('goods_car')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->order('id desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = $v['img'] ? getPicture($v['img']) : getGoodsImg($v['goods_id']);
                $goods_info = Db::name('goods')->where(['id' => $v['goods_id']])->find();
                $v['goods_name'] = $goods_info['name'];
                $v['active'] = false;

                // 商品限购数量
                $v['limit_buy_count'] = $goods_info['limit_buy_count'] ? : 0;

                // 获取商品的价格
                $price = Db::name('sku_value')->where(['sku_id' => $v['sku_id']])->value('price');
                $v['price'] = $price ? : $v['price'];

                if ($sku_list = getSkuName(explode('-', $v['sku_id']))) $v['sku'] = implode('，', array_column($sku_list, 'name'));
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 移除购物车商品
     * */
    public function removeGoodsCar()
    {
        $input = Request()->param();
        $car_ids = $input['car_ids'];
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        $res = Db::name('goods_car')->where(['id' => ['IN', $car_ids]])->delete();
        if ($res) {
            apiReturn(1, '移除成功');
        } else {
            apiReturn(2, '移除失败');
        }
    }

    /**
     * 购物车订单确认页
     * */
    public function goodsCarOrderConfirm()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $shop_id = $input['shop_id'];
        $car_ids = $input['car_ids'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');

        // 用户信息
        $user_info = Db::name('user')->field('id,username,mobile')->where(['id' => $user_id])->find();
        $customer_info = Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->find();
        if (empty($customer_info)) {
            $customer_data = [
                'user_id' => $user_id,
                'shop_id' => $shop_id,
                'create_time' => time()
            ];
            $res = Db::name('customer')->insert($customer_data);
            if (!$res) apiReturn(2, '创建客户信息失败');
        }
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        $car_list = Db::name('goods_car')->field('id,goods_id,img,sku_id,price,count')->where(['id' => ['IN', $car_ids]])->order('id desc')->select();
        $all_price = 0;
        if ($car_list) {
            $pack_price = 0;
            $delivery_price = 0;

            foreach ($car_list as &$v) {
                $goods_info = Db::name('goods')->field('pack_price,delivery_price,name')->where(['id' => $v['goods_id']])->find();

                $delivery_price += $goods_info['delivery_price'] * $v['count'];
                $pack_price += $goods_info['pack_price'] * $v['count'];
                $v['goods_name'] = $goods_info['name'];
                $v['img'] = $v['img'] ? getPicture($v['img']) : getGoodsImg($v['goods_id']);
                $v['sku'] = implode('，', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));

                // 获取商品的价格
                $sku_info = Db::name('sku_value')->field('price,pay_integral')->where(['sku_id' => $v['sku_id']])->find();
                $v['price'] = $sku_info['price'] ? : $v['price'];
                $v['pay_integral'] = $sku_info['pay_integral'];

                $all_price += sprintf("%.2f", $v['price'] * $v['count']);
            }

            //默认收货地址
            $default_address = Db::name('address')->field('id,username,mobile,title,detail_address')->where(['user_id' => $user_id])->order('is_default desc,id desc')->find();
            $default_address['address'] = $default_address['title'] . $default_address['detail_address'];

            //优惠券列表
            $empty_coupon = [
                [
                    'id' => 0,
                    'coupon_name' => '请选择优惠券',
                    'full_price' => 0,
                    'face_price' => 0
                ]
            ];
            $coupon_list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price')->where(['user_id' => $user_id, 'is_del' => 0, 'full_price' => ['elt', $all_price], 'status' => 1])->order('expire_time asc')->select();

            // 实物券列表
            $empty_lottery_coupon = [
                [
                    'id' => 0,
                    'goods_id' => 0,
                    'coupon_name' => '请选择实物券'
                ]
            ];
            $lottery_coupon_list = Db::name('user_lottery_coupon')->field('id,goods_id,coupon_name')->where(['user_id' => $user_id, 'shop_id' => $shop_id, 'is_use' => 0])->select();

            // 默认门店地址
            if ($shop_id) {
                $shop_info = Db::name('shop')->field('id,name,address,business_range_time,booking_range_time')->where(['id' => $shop_id])->find();
                if ($shop_info) $shop_info['address_desc'] = $shop_info['address'];
            }

            // 查询当前抽奖活动信息
            $activity_info = Db::name('activity')->field('id,type,time,full_price,add_price,lottery_coupon_ids')->where(['shop_id' => $shop_id, 'status' => 1])->order('id desc')->find();
            $can_lottery = true;
            if ($activity_info) {
                $time = time();
                $time_arr = explode(' - ', $activity_info['time']);
                if (!($time >= strtotime($time_arr[0]) && $time <= strtotime($time_arr[1]))) {
                    // 不再活动时间内
                    $can_lottery = false;
                }
            } else {
                $can_lottery = false;
            }

            $data = [
                'goods_list' => $car_list,
                'pack_price' => sprintf('%.2f', $pack_price),
                'delivery_price' => sprintf('%.2f', $delivery_price),
                'all_price' => sprintf('%.2f', $all_price),
                'address' => $default_address ? : [],
                'coupon_list' => $coupon_list ? array_merge($empty_coupon, $coupon_list) : $empty_coupon,
                'lottery_coupon_list' => $lottery_coupon_list ? array_merge($empty_lottery_coupon, $lottery_coupon_list) : $empty_lottery_coupon,
                'shop_info' => $shop_info ? : [],
                'user_info' => $user_info,
                'can_lottery' => $can_lottery,
                'activity_info' => $can_lottery ? $activity_info : [],
            ];
            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '购物车商品数据异常');
        }
    }

    /**
     * 购物车立即支付【生成待支付订单】 之后 发起支付
     * */
    public function addGoodsCarOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $shop_id = $input['shop_id'] ? : 0;// shop_id字段用于门店业绩统计
        $car_ids = $input['car_ids'];
        $address_id = $input['address_id'];
        $user_coupon_id = $input['user_coupon_id'];
        $lottery_coupon_id = $input['lottery_coupon_id'];
        $lottery_price = $input['lottery_price'];
        $all_price = $input['all_price'];
        $add_price = $input['add_price'] ? : 0;
        $pay_price = $input['pay_price'];
        $pack_price = $input['pack_price'] ? : 0;
        $send_type = $input['send_type'] ? : 1;
        $delivery_price = $input['delivery_price'] ? : 0;
        $pay_type = $input['pay_type'];
        $is_business = $input['is_business'] ? : 0;
        $arrive_time = $input['arrive_time'];
        $remark = $input['remark'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        if ($pay_type == 1 && empty($all_price)) apiReturn(2, '商品金额错误');
        if ($is_business == 1 && empty($arrive_time)) apiReturn(2, '用餐时间缺失');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        if ($send_type == 1 && empty($address_id)) apiReturn(2, '请选择收货地址');

        $time = time();

        Db::startTrans();
        try {
            $car_list = Db::name('goods_car')->field('id,goods_id,price,sku_id,count')->where(['id' => ['IN', $car_ids]])->select();

            if ($car_list) {
                //支付订单号
                $order_sn = createOrderSn();

                //订单主表添加数据
                if ($user_coupon_id) {
                    $user_coupon_info = Db::name('user_coupon')->where(['id' => $user_coupon_id])->find();

                    // 修改优惠券为已使用状态
                    Db::name('user_coupon')->where(['id' => $user_coupon_id])->update(['status' => 2, 'update_time' => $time]);
                }

                if ($lottery_coupon_id) {
                    $lottery_coupon_info = Db::name('user_lottery_coupon')->where(['id' => $lottery_coupon_id])->find();
                    // 修改实物券为已使用状态
                    Db::name('user_lottery_coupon')->where(['id' => $lottery_coupon_id])->update(['is_use' => 1, 'update_time' => $time]);
                }

                $order_data = [
                    'user_id' => $user_id,
                    'shop_id' => $shop_id ? : 0,
                    'order_sn' => $order_sn,
                    'pay_order_sn' => $order_sn,
                    'user_coupon_id' => $user_coupon_id,
                    'coupon_price' => $user_coupon_info['face_price'] ? : 0,
                    'lottery_coupon_id' => $lottery_coupon_id,
                    'lottery_coupon_name' => $lottery_coupon_info['coupon_name'],
                    'lottery_price' => $lottery_price,
                    'all_price' => $all_price,
                    'add_price' => $add_price,
                    'pay_price' => $pay_price,
                    'pack_price' => $pack_price,
                    'send_type' => $send_type,
                    'delivery_price' => $delivery_price,
                    'pay_type' => $pay_type,
                    'is_business' => $is_business,
                    'arrive_time' => $is_business == 1 ? str_replace('今天', date('Y-m-d'), $arrive_time) : '',
                    'remark' => $remark,
                    'car_ids' => $car_ids,
                    'create_time' => $time
                ];

                if ($send_type == 1) {
                    $address_info = Db::name('address')->where(['id' => $address_id])->find();
                    $order_data['get_username'] = $address_info['username'];
                    $order_data['get_mobile'] = $address_info['mobile'];
                    $order_data['get_sex'] = $address_info['sex'];
                    $order_data['get_address'] = $address_info['title'] . $address_info['detail_address'];
                    $order_data['get_lat'] = $address_info['lat'];
                    $order_data['get_lng'] = $address_info['lng'];
                }

                $send_integral = 0;
                $use_integral = 0;
                $goods_order = [];
                $count = 0;// 商品总数量，抽奖需要用到

                // 抽奖活动信息
                $activity_info = Db::name('activity')->field('id,type,time,full_price,add_price,lottery_coupon_ids')->where(['shop_id' => $shop_id, 'status' => 1])->order('id desc')->find();

                foreach ($car_list as &$v) {
                    $goods_info = Db::name('goods')->field('id,name')->where(['id' => $v['goods_id']])->find();

                    $sku_info = Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();
                    if ($sku_info) {
                        //                        if ($v['count'] > $sku_info['stock']) apiReturn(2, $goods_info['name'] . '库存不足');

                        if ($add_price > 0 || $sku_info['price'] >= $activity_info['full_price']) $count += $v['count'];

                        if ($pay_type == 2) {
                            $use_integral += $sku_info['pay_integral'] * $v['count'];
                        } else {
                            if ($sku_info['send_integral'] > 0) $send_integral += $sku_info['send_integral'] * $v['count'];
                        }
                    } else {
                        apiReturn(2, $goods_info['name'] . '属性不存在或已删除');
                    }

                    //准备订单副表数据
                    $goods_info = Db::name('goods')->field('id,name')->where(['id' => $v['goods_id']])->find();
                    $sku_info = Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();

                    $goods_order[] = [
                        'goods_id' => $v['goods_id'],
                        'sku_id' => $sku_info['sku_id'],
                        'img' => $sku_info['img'],
                        'name' => $goods_info['name'],
                        'price' => $sku_info['price'],
                        'count' => $v['count'],
                        'create_time' => $time
                    ];
                }

                $order_data['send_integral'] = $send_integral;
                $order_data['use_integral'] = $use_integral;

                $order_id = Db::name('order')->insertGetId($order_data);

                // 抽奖信息添加
                if ($add_price > 0) {
                    // 参加了加多少元抽奖活动
                    $can_lottery = true;
                } else {
                    // 查询是否满足参加满额抽奖活动
                    $can_lottery = true;
                    if ($activity_info) {
                        $time = time();
                        $time_arr = explode(' - ', $activity_info['time']);

                        if (!($time >= strtotime($time_arr[0]) && $time <= strtotime($time_arr[1]))) {
                            // 不再活动时间内
                            $can_lottery = false;
                        } else {
                            if ($count == 0) $can_lottery = false;
                        }
                    } else {
                        $can_lottery = false;
                    }
                }

                if ($can_lottery) {
                    $order_lottery_data = [
                        'user_id' => $user_id,
                        'shop_id' => $shop_id,
                        'order_id' => $order_id,
                        'activity_id' => $activity_info['id'],
                        'count' => $count,
                        'can_count' => $count,
                        'status' => 0
                    ];
                    Db::name('order_lottery')->insert($order_lottery_data);
                }

                if ($use_integral) {
                    // 积分扣除（下单有积分扣除即：积分抵扣商品）
                    $integral_data = [
                        'user_id' => $user_id,
                        'shop_id' => $shop_id,
                        'integral' => '-' . $use_integral,
                        'type' => 2,
                        'order_id' => $order_id,
                        'create_time' => $time
                    ];
                    Db::name('integral_log')->insert($integral_data);

                    Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->setDec('integral', $use_integral);
                }

                if ($goods_order) {
                    foreach ($goods_order as &$v) {
                        $v['order_id'] = $order_id;
                    }
                }

                $vice_order_res = Db::name('vice_order')->insertAll($goods_order);

                if ($vice_order_res) {
                    // 清除对应购物车商品
                    Db::name('goods_car')->where(['id' => ['IN', $car_ids]])->delete();

                    if ($pay_price > 0) {
                        //微信支付
                        Loader::import('wxsdk\wxPay', EXTEND_PATH);
                        $obj = new \wxPay();
                        //调用示例（最后两个参数为可选参数）
                        $pay_price = C('TEST_PAY') ? 0.01 : $pay_price;
                        $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '商品支付', getHost() . '/index/Notify/notice', '', 1);

                        $return_data = [
                            'pay_data' => $pay_data,
                            'order_sn' => $order_sn
                        ];
                    } else {
                        action('Index/Notify/doGoodsOrder', $order_sn);
                    }

                    Db::commit();
                    apiReturn(1, '获取数据成功', $return_data);
                } else {
                    Db::rollback();
                    apiReturn(2, '订单生成失败');
                }
            } else {
                Db::rollback();
                apiReturn(2, '购物车商品数据异常');
            }
        } catch (\Exception $e) {
            apiReturn(2, '系统繁忙，请稍后再试' . $e);
        }
    }

    /**
     * 商品确认订单
     * */
    public function confirmOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $shop_id = $input['shop_id'];
        $goods_id = $input['goods_id'];
        $sku_id = $input['sku_id'];
        $count = $input['count'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($shop_id)) apiReturn(2, '门店ID缺失');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if (empty($count)) apiReturn(2, '商品数量异常');

        $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
        $goods_img = $goods_info['img'];
        $pack_price = $goods_info['pack_price'] * $count;        // 商品打包费
        $delivery_price = $goods_info['delivery_price'] * $count;// 商品配送费

        $sku_info = Db::name('sku_value')->field('sku_id,img,price,goods_id,pay_integral,send_integral')->where(['sku_id' => $sku_id, 'goods_id' => $goods_id])->find();
        if ($sku_info) {
            $sku_info['goods_name'] = Db::name('goods')->where(['id' => $sku_info['goods_id']])->value('name');
            $sku_info['img'] = getPicture($sku_info['img']);
            $sku_info['sku'] = implode('，', array_column(getSkuName(explode('-', $sku_info['sku_id'])), 'name'));
            $all_price = sprintf("%.2f", $sku_info['price'] * $count);

            //默认收货地址
            $default_address = Db::name('address')->field('id,username,mobile,title,detail_address')->where(['user_id' => $user_id])->order('is_default desc,id desc')->find();
            $default_address['address'] = $default_address['title'] . $default_address['detail_address'];
            unset($default_address['title'], $default_address['detail_address']);

            //优惠券列表
            $empty_coupon = [
                [
                    'id' => 0,
                    'coupon_name' => '请选择优惠券',
                    'full_price' => 0,
                    'face_price' => 0
                ]
            ];
            $coupon_list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price')->where(['user_id' => $user_id, 'shop_id' => $shop_id, 'is_del' => 0, 'full_price' => ['elt', $all_price], 'status' => 1])->order('expire_time asc')->select();

            // 实物券列表
            $empty_lottery_coupon = [
                [
                    'id' => 0,
                    'goods_id' => 0,
                    'coupon_name' => '请选择实物券'
                ]
            ];
            $lottery_coupon_list = Db::name('user_lottery_coupon')->field('id,goods_id,coupon_name')->where(['user_id' => $user_id, 'shop_id' => $shop_id, 'is_use' => 0])->select();

            // 用户信息
            $user_info = Db::name('user')->field('id,username,mobile')->where(['id' => $user_id])->find();

            // 查询当前抽奖活动信息
            $activity_info = Db::name('activity')->field('id,type,time,full_price,add_price,lottery_coupon_ids')->where(['shop_id' => $shop_id, 'status' => 1])->order('id desc')->find();
            $can_lottery = true;
            if ($activity_info) {
                $time = time();
                $time_arr = explode(' - ', $activity_info['time']);

                if (!($time >= strtotime($time_arr[0]) && $time <= strtotime($time_arr[1]))) {
                    // 不再活动时间内
                    $can_lottery = false;
                }
            } else {
                $can_lottery = false;
            }

            // 查询门店营业时间和预订时间
            $shop_info = Db::name('shop')->field('business_range_time,booking_range_time')->where(['id' => $shop_id])->find();

            $data = [
                'goods_img' => getPicture($goods_img),
                'pack_price' => sprintf('%.2f', $pack_price),
                'delivery_price' => sprintf('%.2f', $delivery_price),
                'goods_info' => $sku_info,
                'all_price' => $all_price,
                'address' => $default_address ? : [],
                'coupon_list' => $coupon_list ? array_merge($empty_coupon, $coupon_list) : $empty_coupon,
                'lottery_coupon_list' => $lottery_coupon_list ? array_merge($empty_lottery_coupon, $lottery_coupon_list) : $empty_lottery_coupon,
                'user_info' => $user_info,
                'can_lottery' => $can_lottery,
                'activity_info' => $can_lottery ? $activity_info : [],
                'shop_info' => $shop_info
            ];

            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '规格不存在或已删除');
        }
    }

    /**
     * 立即支付【生成待支付订单】 之后 发起支付
     * */
    public function addGoodsOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $shop_id = $input['shop_id'] ? : 0;
        $goods_id = $input['goods_id'];
        $count = $input['count'];
        $sku_id = $input['sku_id'];
        $user_coupon_id = $input['user_coupon_id'];
        $lottery_coupon_id = $input['lottery_coupon_id'];
        $lottery_price = $input['lottery_price'] ? : 0;
        $all_price = $input['all_price'];
        $add_price = $input['add_price'] ? : 0;
        $pay_price = $input['pay_price'];
        $pack_price = $input['pack_price'] ? : 0;
        $send_type = $input['send_type'] ? : 1;
        $delivery_price = $input['delivery_price'] ? : 0;
        $address_id = $input['address_id'];
        $pay_type = $input['pay_type'];
        $is_business = $input['is_business'] ? : 0;
        $arrive_time = $input['arrive_time'];
        $remark = $input['remark'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if ($count <= 0) apiReturn(2, '商品数量异常');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if ($pay_type == 1 && empty($all_price)) apiReturn(2, '商品金额错误');
        if ($is_business == 1 && empty($arrive_time)) apiReturn(2, '用餐时间缺失');

        $sku_info = Db::name('sku_value')->where(['sku_id' => $sku_id, 'goods_id' => $goods_id])->find();

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        $customer_info = Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->find();
        if (empty($customer_info)) {
            $customer_data = [
                'user_id' => $user_id,
                'shop_id' => $shop_id,
                'create_time' => time()
            ];
            $res = Db::name('customer')->insert($customer_data);
            if (!$res) apiReturn(2, '创建客户信息失败');
        }
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');
        if ($customer_info['integral'] < $sku_info['pay_integral'] && $pay_type == 2) apiReturn(2, '积分不足');

        if ($send_type == 1 && empty($address_id)) apiReturn(2, '请选择收货地址');

        $time = time();

        Db::startTrans();
        try {
            $goods_info = Db::name('goods')->field('id,name')->where(['id' => $goods_id])->find();
            if ($goods_info) {
                if ($sku_info) {
                    //商品库存
                    //                    if ($count > $sku_info['stock']) apiReturn(2, '商品库存不足');

                    $order_sn = createOrderSn();

                    //订单主表添加数据
                    if ($user_coupon_id) {
                        $user_coupon_info = Db::name('user_coupon')->where(['id' => $user_coupon_id])->find();
                        // 修改优惠券为已使用状态
                        Db::name('user_coupon')->where(['id' => $user_coupon_id])->update(['status' => 2, 'update_time' => $time]);
                    }

                    $lottery_coupon_name = '';
                    if ($lottery_coupon_id) {
                        $lottery_coupon_info = Db::name('user_lottery_coupon')->where(['id' => $lottery_coupon_id])->find();
                        $lottery_coupon_name = $lottery_coupon_info['coupon_name'];
                        // 修改实物券为已使用状态
                        Db::name('user_lottery_coupon')->where(['id' => $lottery_coupon_id])->update(['is_use' => 1, 'update_time' => $time]);
                    }

                    $data = [
                        'user_id' => $user_id,
                        'shop_id' => $shop_id ? : 0,
                        'order_sn' => $order_sn,
                        'pay_order_sn' => $order_sn,
                        'user_coupon_id' => $user_coupon_id,
                        'coupon_price' => $user_coupon_info['face_price'] ? : 0,
                        'lottery_coupon_id' => $lottery_coupon_id,
                        'lottery_coupon_name' => $lottery_coupon_name,
                        'lottery_price' => $lottery_price,
                        'all_price' => $all_price,
                        'add_price' => $add_price,
                        'pay_price' => $pay_price,
                        'pack_price' => $pack_price,
                        'send_type' => $send_type,
                        'delivery_price' => $delivery_price,
                        'pay_type' => $pay_type,
                        'is_business' => $is_business,
                        'arrive_time' => $is_business == 1 ? str_replace('今天', date('Y-m-d'), $arrive_time) : '',
                        'remark' => $remark,
                        'create_time' => $time
                    ];

                    if ($send_type == 1) {
                        $address_info = Db::name('address')->where(['id' => $address_id])->find();
                        $data['get_username'] = $address_info['username'];
                        $data['get_mobile'] = $address_info['mobile'];
                        $data['get_sex'] = $address_info['sex'];
                        $data['get_address'] = $address_info['title'] . $address_info['detail_address'];
                        $data['get_lat'] = $address_info['lat'];
                        $data['get_lng'] = $address_info['lng'];
                    }

                    if ($pay_type == 2) {
                        $use_integral = $sku_info['pay_integral'];
                        $data['use_integral'] = $use_integral;
                    } else {
                        if ($sku_info['send_integral'] > 0) $data['send_integral'] = $sku_info['send_integral'];
                    }


                    $order_id = Db::name('order')->insertGetId($data);

                    // 抽奖信息添加
                    $activity_info = Db::name('activity')->field('id,type,time,full_price,add_price,lottery_coupon_ids')->where(['shop_id' => $shop_id, 'status' => 1])->order('id desc')->find();
                    if ($add_price > 0) {
                        // 参加了加多少元抽奖活动
                        $can_lottery = true;
                    } else {
                        // 查询是否满足参加满额抽奖活动
                        $can_lottery = true;
                        if ($activity_info) {
                            $time = time();
                            $time_arr = explode(' - ', $activity_info['time']);

                            if (!($time >= strtotime($time_arr[0]) && $time <= strtotime($time_arr[1]))) {
                                // 不再活动时间内
                                $can_lottery = false;
                            } else {
                                if ($sku_info['price'] < $activity_info['full_price']) {
                                    // 单价不满足参加满额抽奖活动
                                    $can_lottery = false;
                                }
                            }
                        } else {
                            $can_lottery = false;
                        }
                    }

                    if ($can_lottery) {
                        $order_lottery_data = [
                            'user_id' => $user_id,
                            'shop_id' => $shop_id,
                            'order_id' => $order_id,
                            'activity_id' => $activity_info['id'],
                            'count' => $count,
                            'can_count' => $count,
                            'status' => 0
                        ];
                        Db::name('order_lottery')->insert($order_lottery_data);
                    }

                    if ($use_integral) {
                        // 积分扣除（下单有积分扣除即：积分抵扣商品）
                        $integral_data = [
                            'user_id' => $user_id,
                            'shop_id' => $shop_id,
                            'integral' => '-' . $use_integral,
                            'type' => 2,
                            'order_id' => $order_id,
                            'create_time' => $time
                        ];
                        Db::name('integral_log')->insert($integral_data);

                        Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->setDec('integral', $use_integral);
                    }

                    $goods_order = [
                        'order_id' => $order_id,
                        'goods_id' => $goods_id,
                        'sku_id' => $sku_id,
                        'img' => $sku_info['img'],
                        'name' => $goods_info['name'],
                        'price' => $sku_info['price'],
                        'count' => $count,
                        'create_time' => $time
                    ];
                    Db::name('vice_order')->insert($goods_order);

                    if ($pay_price > 0) {
                        // 调用微信支付
                        Loader::import('wxsdk\wxPay', EXTEND_PATH);
                        $obj = new \wxPay();
                        //调用示例（最后两个参数为可选参数）
                        $pay_price = C('TEST_PAY') ? 0.01 : $pay_price;
                        $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '商品支付', getHost() . '/Index/Notify/notice');

                        $return_data = [
                            'pay_data' => $pay_data,
                            'order_sn' => $order_sn
                        ];
                    } else {
                        action('Index/Notify/doGoodsOrder', $order_sn);
                    }

                    Db::commit();
                    apiReturn(1, '获取数据成功', $return_data ? : []);
                } else {
                    Db::rollback();
                    apiReturn(2, '规格不存在或已删除');
                }
            } else {
                Db::rollback();
                apiReturn(2, '商品不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试' . $e);
        }
    }

    /**
     * 收货地址列表
     * */
    public function addressList()
    {
        $input = Request()->param();
        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('address')->where(['user_id' => $user_id])->order('is_default desc,create_time desc')->select();
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无收货地址', []);
        }
    }

    /**
     * 收货地址详情
     * */
    public function addressDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');

        $info = Db::name('address')->where(['id' => $id])->find();
        if ($info) {
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '收货地址不存在或已删除');
        }
    }

    /**
     * 添加收货地址
     * */
    public function doAddress()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $username = $input['username'];
        $mobile = $input['mobile'];
        $sex = $input['sex'];
        $title = $input['title'];
        $address = $input['address'];
        $detail_address = $input['detail_address'];
        $lat = $input['lat'];
        $lng = $input['lng'];
        $is_default = $input['is_default'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($lat) || empty($lng) || empty($address) || empty($title)) apiReturn(2, '请选择位置');
        if (empty($detail_address)) apiReturn(2, '请输入门牌号');
        if (empty($username)) apiReturn(2, '请填写联系人');
        if (empty($mobile)) apiReturn(2, '请填写手机号');

        $time = time();
        $data = [
            'user_id' => $user_id,
            'username' => $username,
            'mobile' => $mobile,
            'sex' => $sex,
            'title' => $title,
            'address' => $address,
            'detail_address' => $detail_address,
            'lat' => $lat,
            'lng' => $lng,
            'is_default' => $is_default,
        ];
        if ($is_default == 1) Db::name('address')->where(['user_id' => $user_id])->setField('is_default', 0);

        if ($id) {
            $data['update_time'] = $time;
            $res = Db::name('address')->where(['id' => $id])->update($data);
        } else {
            $data['create_time'] = $time;
            $res = Db::name('address')->insert($data);
        }

        if ($res) {
            apiReturn(1, '添加成功');
        } else {
            apiReturn(2, '添加失败');
        }
    }

    /**
     * 设置默认地址
     * */
    public function setDefaultAddress()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('address')->where(['id' => $id])->find();
            if ($info) {
                Db::name('address')->where(['user_id' => $info['user_id']])->setField('is_default', 0);
                Db::name('address')->where(['id' => $id])->setField('is_default', 1);

                Db::commit();
                apiReturn(1, '设置成功');
            } else {
                Db::rollback();
                apiReturn(2, '收货地址不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '设置失败');
        }
    }

    /**
     * 删除收货地址
     * */
    public function delAddress()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');

        $info = Db::name('address')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('address')->where(['id' => $id])->delete();
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '收货地址不存在或已删除');
        }
    }

    /**
     * 最新消息
     * */
    public function msgList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('msg')->where(['user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d H:i:s');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 分类消息列表
     * */
    public function msgListBak()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $type = $input['type'] ? : 1;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        // 分页起始位置
        $offset = ($page - 1) * $pagesize;
        // 未读信息条件
        $where = '(user_id = ' . $user_id . ' or user_id = 0) and type = ' . $type;
        // 未读
        $sql = 'select id,order_id,title,content,read_user,type,create_time from ' . config('database.prefix') . 'msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
        $list = Db::name('msg')->query($sql);
        if ($list) {
            foreach ($list as &$v) {
                $v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
                $v['content'] = doEditorContent($v['content']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 消息详情
     * */
    public function msgDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '消息ID缺失');

        $info = Db::name('msg')->field('id,title,content,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time'], 'Y-m-d H:i');

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '消息不存在或已删除');
        }
    }

    /**
     * 消息详情
     * */
    public function msgDetailBak()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($id)) apiReturn(2, '消息ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('msg')->field('id,title,content,read_user,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i');

            Db::name('msg')->where(['id' => $id])->setInc('look_count');

            $is_read = in_array($user_id, explode(',', $info['read_user'])) ? true : false;
            if (!$is_read) Db::name('msg')->where(['id' => $id])->setField('read_user', $info['read_user'] ? $info['read_user'] . ',' . $user_id : $user_id);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '消息不存在或已删除');
        }
    }

    /**
     * 个人中心
     * */
    public function userCenter()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $shop_id = $input['shop_id'];

        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($shop_id)) apiReturn(2, '门店ID缺失');

        $info = Db::name('user u')
            ->join('cater_customer c', 'u.id = c.user_id', 'left')
            ->field('c.id,c.user_id,u.avatar,u.username,u.mobile,c.integral')
            ->where(['u.id' => $user_id, 'c.shop_id' => $shop_id])
            ->find();

        if ($info) {
            $info['hide_mobile'] = hideMobile($info['mobile']);
            $info['avatar'] = doAvatar($info['avatar']);

            // 待使用优惠券数量
            $coupon_count = Db::name('user_coupon')->where(['user_id' => $user_id, 'shop_id' => $shop_id, 'status' => 1, 'expire_time' => ['egt', date('Y-m-d')], 'is_del' => 0])->count();
            $info['coupon_count'] = $coupon_count;

            // 待使用的实物券数量
            $lottery_coupon_count = Db::name('user_lottery_coupon')->where(['user_id' => $user_id, 'shop_id' => $shop_id, 'is_use' => 0])->count();
            $info['lottery_coupon_count'] = $lottery_coupon_count;

            $order_where = [
                'user_id' => $user_id,
                'shop_id' => $shop_id,
                'is_pay' => 1,
                'is_del' => 0,
                'back_order_sn' => ''
            ];
            // 待配送订单数量
            $wait_get_order_count = Db::name('order')->where($order_where)->where(['status' => 2])->count();
            // 待评价订单数量
            $wait_comment_order_count = Db::name('order')->where($order_where)->where(['status' => 4])->count();
            // 售后中订单数量
            $after_order_count = Db::name('order')->where($order_where)->where(['status' => 6])->count();
            // 待付款订单数量
            $order_where['is_pay'] = 0;
            $wait_pay_order_count = Db::name('order')->where($order_where)->where(['status' => 1])->count();

            $info['wait_pay_order_count'] = $wait_pay_order_count;
            $info['wait_get_order_count'] = $wait_get_order_count;
            $info['wait_comment_order_count'] = $wait_comment_order_count;
            $info['after_order_count'] = $after_order_count;

            // 门店电话
            $shop_mobile = Db::name('shop')->where(['id' => $shop_id])->value('mobile');
            $info['shop_mobile'] = $shop_mobile;


            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '用户不存在或已禁用');
        }
    }

    /**
     * 我的收益详情
     * */
    public function userProfit()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        // 自己消费总额
        $me_all_consume = $this->getMeConsume($user_id);

        // 总累计销售额 = 我和我的所有下线的消费统计
        $all_consume = $me_all_consume + action('Algorithm/Algorithm/allConsume', ['user_id' => $user_id]);
        /**
         * 个人零售销售额 = 自己消费总额中除去自己首次消费金额
         * */
        // 自己首次消费金额
        $first_consume = Db::name('order')->where(['user_id' => $user_id, 'is_pay' => 1, 'complete_time' => ['neq', 0]])->order('id asc')->value('pay_price');
        // 个人零售销售额 = 自己消费总额 - 自己首次消费金额
        $me_consume = sprintf('%.2f', $me_all_consume - $first_consume);

        $profit_where = [
            'user_id' => $user_id,
            'status' => ['neq', -1],
            'type' => ['IN', [1, 2, 3]]
        ];
        // 总累计收益
        $all_profit = Db::name('profit')->where($profit_where)->sum('price');
        // 可用收益
        $normal_profit = Db::name('user')->where(['id' => $user_id])->value('all_profit');
        // 冻结收益
        $frozen_profit = Db::name('profit')->where($profit_where)->where(['status' => 1])->sum('price');

        $info = [
            'all_consume' => sprintf('%.2f', $all_consume),
            'me_consume' => sprintf('%.2f', $me_consume),
            'all_profit' => sprintf('%.2f', $all_profit),
            'normal_profit' => sprintf('%.2f', $normal_profit),
            'frozen_profit' => sprintf('%.2f', $frozen_profit),
        ];

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 收益明细
     * */
    public function profitList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $profit_where = [
            'user_id' => $user_id,
            'status' => ['neq', -1]
        ];
        $profit_list = Db::name('profit')->field('id,order_id,user_id,type,price,remark,create_time')->where($profit_where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($profit_list) {
            foreach ($profit_list as &$v) {
                if ($v['type'] == 1 || $v['type'] == 2 || $v['type'] == 3) {
                    $pay_user_id = Db::name('order')->where(['id' => $v['order_id']])->value('user_id');
                    if ($pay_user_id) {
                        $user_info = Db::name('user')->field('username,gender')->where(['id' => $pay_user_id])->find();
                        $username = cutSubstr($user_info['username']);
                        if (mb_strlen($username) > 6) $username = cutSubstr($username, 6);
                    }
                } else {
                    $username = '';
                }

                switch ($v['type']) {
                    case 2:
                    case 1:
                        $desc = ' 成功购买了商品';
                        $change = 'plus';
                        break;
                    case 3:
                        $desc = '消费，您获得服务津贴';
                        $change = 'plus';
                        break;
                    case 4:
                        $desc = '购物收益抵扣';
                        $change = 'minus';
                        break;
                    case 5:
                        $desc = '收益提现';
                        $change = 'minus';
                        break;
                    case 6:
                    case 7:
                    case 9:
                        $desc = $v['remark'];
                        $change = 'plus';
                        break;
                    case 8:
                        $desc = '收益提现审核失败，收益返还';
                        $change = 'plus';
                        break;
                    case 10:
                        $desc = '充值收益';
                        $change = 'plus';
                        break;
                    case 11:
                        $desc = '处罚收益';
                        $change = 'minus';
                        break;
                    case 12:
                        $desc = '购物抵扣收益退款';
                        $change = 'plus';
                        break;
                }

                $v['username'] = $username;
                $v['desc'] = $desc;
                $v['change'] = $change;

                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $profit_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 提现记录
     * */
    public function withdrawalList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('withdrawal')->field('id,real_price price,type,status,create_time')->where(['user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['desc'] = $v['status'] == 1 ? '提现到' . ($v['type'] == 1 ? '微信钱包' : '银行卡') : '提现审核失败';
                $v['change'] = $v['status'] == 1 ? 'plus' : 'minus';
                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 提现页面数据回显
     * */
    public function withdrawalInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $user_info = Db::name('user')->field('id,all_profit,real_name,bank_name,bank_num,bank_deposit')->where(['id' => $user_id])->find();

        $empty_bank = ['请选择'];
        $bank_list = C('BANK_LIST');
        $bank_list = array_merge($empty_bank, $bank_list);
        $bankIndex = 0;
        if ($bank_list) {
            foreach ($bank_list as $k => &$v) {
                if ($user_info['bank_name'] == $v) {
                    $bankIndex = $k;
                    break;
                }
            }
        }

        $withdrawal_price = C('WITHDRAWAL_PRICE');

        $service_rate = C('SERVICE_RATE');

        $data = [
            'user_info' => $user_info,
            'bank_list' => $bank_list,
            'bankIndex' => $bankIndex,
            'withdrawal_price' => $withdrawal_price,
            'service_rate' => $service_rate
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 申请提现
     * */
    public function applyWithdrawal()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $price = $input['price'];
        $service_rate = $input['service_rate'];
        $real_price = $input['real_price'];
        $real_name = $input['real_name'];
        $bank_name = $input['bank_name'];
        $bank_num = $input['bank_num'];
        $bank_deposit = $input['bank_deposit'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($price)) apiReturn(2, '请输入提现金额');
        if (empty($real_price)) apiReturn(2, '实际到账金额错误');

        $time = time();

        $withdrawal_price = C('WITHDRAWAL_PRICE');

        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d')) + 24 * 3600 - 1;
        $count = Db::name('withdrawal')->where(['user_id' => $user_id, 'status' => ['neq', 2], 'create_time' => ['between', [$start_time, $end_time]]])->count();
        if ($count) apiReturn(2, '每号每天限提一次');

        Db::startTrans();
        try {
            $user_info = Db::name('user')->where(['id' => $user_id])->find();

            $order_sn = uniqid();                //订单号

            if ($price <= $withdrawal_price) {
                if (empty($user_info['openid'])) apiReturn(2, 'openid缺失');

                // 提现到微信零钱
                $mchid = C('MCH_ID');          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
                $appid = C('XCX_APPID');       //微信支付申请对应的公众号的APPID
                $appKey = C('XCX_SECRET');     //微信支付申请对应的公众号的APP Key
                $apiKey = C('MCH_KEY');        //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥

                Loader::import('weixinPay\weixinPay-master\transfers', EXTEND_PATH);
                $obj = new \WxpayService($mchid, $appid, $appKey, $apiKey);

                $obj->createJsBizPackage($user_info['openid'], $price, $order_sn, $real_name);

                $data = [
                    'order_sn' => $order_sn,
                    'user_id' => $user_id,
                    'price' => $price,
                    'type' => 1,
                    'create_time' => $time
                ];
                Db::name('withdrawal')->insert($data);
            } else {
                if (empty($real_name) || $real_name == 'undefined') apiReturn(2, '姓名信息异常，请重新输入');
                if (empty($bank_name) || $bank_name == 'undefined' || $bank_name == '请选择') apiReturn(2, '请选择银行');
                if (empty($bank_num) || $bank_num == 'undefined') apiReturn(2, '银行卡号信息异常，请重新输入');
                if (empty($bank_deposit) || $bank_deposit == 'undefined') apiReturn(2, '开户行信息异常，请重新输入');

                // 申请提现到银行卡
                $data = [
                    'order_sn' => $order_sn,
                    'user_id' => $user_id,
                    'price' => $price,
                    'rate' => $service_rate,
                    'service_price' => $price - $real_price,
                    'real_price' => $real_price,
                    'type' => 2,
                    'real_name' => $real_name,
                    'bank_name' => $bank_name,
                    'bank_num' => $bank_num,
                    'bank_deposit' => $bank_deposit,
                    'create_time' => $time
                ];
                Db::name('withdrawal')->insert($data);
            }

            $user_data = [
                'all_profit' => $user_info['all_profit'] - $price,
                'real_name' => $real_name,
                'bank_name' => $bank_name,
                'bank_num' => $bank_num,
                'bank_deposit' => $bank_deposit
            ];
            Db::name('user')->where(['id' => $user_id])->update($user_data);

            Db::commit();
            apiReturn(1, '申请提现成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~' . $e);
        }
    }

    /**
     * 订单列表
     * */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;
        $list = Db::name('order')->field('id,order_sn,pay_price,status,hx_qr')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['status_desc'] = doOrderStatus($v['status']);

                // 查询订单抽奖表信息，看是否可以抽奖
                $order_lottery_info = Db::name('order_lottery')->where(['order_id' => $v['id']])->find();
                if ($v['status'] == 4 || $v['status'] == 5) {
                    if ($order_lottery_info['status'] == 1) {
                        $can_lottery = true;
                    } else {
                        $can_lottery = false;
                    }
                } else {
                    $can_lottery = false;
                }

                $v['can_lottery'] = $can_lottery;
                $v['will_can_lottery'] = (bool)$order_lottery_info;

                $goods_list = Db::name('vice_order')->field('id,img,name,price,count,sku_id,goods_id')->where(['order_id' => $v['id']])->select();
                if ($goods_list) {
                    foreach ($goods_list as &$val) {
                        $val['img'] = $val['img'] ? getPicture($val['img']) : getGoodsImg($val['goods_id']);
                        if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                    }
                    $v['goods_list'] = $goods_list;
                }

                if ($v['status'] == 10) $v['hx_qr'] = getHost() . $v['hx_qr'];
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    public function againQr()
    {
        $input = Request()->param();

        $id = $input['id'];

        if(empty($id)) apiReturn(2,'ID缺失');

        againRreateOrderHxQr($id);
    }

    /**
     * 检查核销订单状态
     * */
    public function checkHxOrder()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $status = Db::name('order')->where(['id' => $id])->value('status');
        if ($status == 4) {
            apiReturn(1, '核销成功');
        } else {
            apiReturn(2, '待核销');
        }
    }

    /**
     * 订单详情
     * */
    public function orderDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id])->find();

        if ($info) {
            $info['create_time'] = timeFormat($info['create_time']);
            $info['status_desc'] = doOrderStatus($info['status']);
            $info['verify_qr'] = getPicture($info['verify_qr']);

            if ($shipper_id = $info['shipper_id']) $info['shipper_name'] = Db::name('shipper')->where(['id' => $shipper_id])->value('name');

            if ($shop_id = $info['shop_id']) {
                $shop_info = Db::name('shop')->where(['id' => $shop_id])->find();
                $shop_info['shop_address'] = $shop_info['address'];
                $info['shop_info'] = $shop_info ? : [];
            }

            $coupon_price = 0;
            if ($user_coupon_id = $info['user_coupon_id']) $coupon_price = Db::name('user_coupon')->where(['id' => $user_coupon_id])->value('face_price');
            $info['coupon_price'] = sprintf('%.2f', $coupon_price);

            if ($shipper_id = $info['shipper_id']) $info['shipper_name'] = Db::name('shipper')->where(['id' => $shipper_id])->value('name');

            $goods_list = Db::name('vice_order')->field('id,goods_id,img,name,price,count,sku_id')->where(['order_id' => $id])->select();
            if ($goods_list) {
                foreach ($goods_list as &$val) {
                    $val['img'] = $val['img'] ? getPicture($val['img']) : getGoodsImg($val['goods_id']);
                    if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                }

                $info['goods_list'] = $goods_list;
            }

            // 查询订单抽奖表信息，看是否可以抽奖
            $order_lottery_info = Db::name('order_lottery')->where(['order_id' => $id])->find();
            if ($info['status'] == 4 || $info['status'] == 5) {
                if ($order_lottery_info['status'] == 1) {
                    $can_lottery = true;
                } else {
                    $can_lottery = false;
                }
            } else {
                $can_lottery = false;
            }
            $info['can_lottery'] = $can_lottery;
            $info['will_can_lottery'] = (bool)$order_lottery_info;

            if ($info['send_type'] == 3) {
                if (!$info['hx_qr']) $info['hx_qr'] = createOrderHxQr($id);
                $info['hx_qr'] = getHost() . $info['hx_qr'];
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 订单详情
     * */
    public function hxOrderDetail()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $info = Db::name('order')->where(['id' => $id])->find();

        if ($info) {
            $is_staff = Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $info['shop_id']])->value('is_staff');
            if (!$is_staff) apiReturn(2, '无核销订单权限');

            $info['create_time'] = timeFormat($info['create_time']);
            $info['status_desc'] = doOrderStatus($info['status']);
            $info['verify_qr'] = getPicture($info['verify_qr']);

            if ($shipper_id = $info['shipper_id']) $info['shipper_name'] = Db::name('shipper')->where(['id' => $shipper_id])->value('name');

            if ($shop_id = $info['shop_id']) {
                $shop_info = Db::name('shop')->where(['id' => $shop_id])->find();
                $shop_info['shop_address'] = $shop_info['address'];
                $info['shop_info'] = $shop_info ? : [];
            }

            $coupon_price = 0;
            if ($user_coupon_id = $info['user_coupon_id']) $coupon_price = Db::name('user_coupon')->where(['id' => $user_coupon_id])->value('face_price');
            $info['coupon_price'] = sprintf('%.2f', $coupon_price);

            if ($shipper_id = $info['shipper_id']) $info['shipper_name'] = Db::name('shipper')->where(['id' => $shipper_id])->value('name');

            $goods_list = Db::name('vice_order')->field('id,goods_id,img,name,price,count,sku_id')->where(['order_id' => $id])->select();
            if ($goods_list) {
                foreach ($goods_list as &$val) {
                    $val['img'] = $val['img'] ? getPicture($val['img']) : getGoodsImg($val['goods_id']);
                    if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                }

                $info['goods_list'] = $goods_list;
            }

            // 查询订单抽奖表信息，看是否可以抽奖
            $order_lottery_info = Db::name('order_lottery')->where(['order_id' => $id])->find();
            if ($info['status'] == 4 || $info['status'] == 5) {
                if ($order_lottery_info['status'] == 1) {
                    $can_lottery = true;
                } else {
                    $can_lottery = false;
                }
            } else {
                $can_lottery = false;
            }
            $info['can_lottery'] = $can_lottery;
            $info['will_can_lottery'] = (bool)$order_lottery_info;

            if ($info['send_type'] == 3) {
                if (!$info['hx_qr']) $info['hx_qr'] = createOrderHxQr($id);
                $info['hx_qr'] = getHost() . $info['hx_qr'];
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 核销订单
     * */
    public function confirmHx()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('order')->where(['id' => $id])->find();
        if ($info) {
            $is_staff = Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $info['shop_id']])->value('is_staff');
            if ($is_staff) {
                Db::startTrans();
                try {
                    Db::name('order')->where(['id' => $id])->setField('status', 4);

                    // 订单抽奖表对应记录修改为可抽奖
                    Db::name('order_lottery')->where(['order_id' => $id])->update(['status' => 1]);

                    Db::commit();
                    apiReturn(1, '核销成功');
                } catch (\Exception $e) {
                    Db::rollback();
                    apiReturn(2, '核销失败或已核销');
                }


            } else {
                apiReturn(2, '无核销订单权限');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 确认收货
     * */
    public function confirmGet()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                Db::name('order')->where(['id' => $id])->update(['status' => 4, 'update_time' => time()]);

                if ($send_integral = $info['send_integral']) {
                    $integral_data = [
                        'user_id' => $info['user_id'],
                        'shop_id' => $info['shop_id'],
                        'integral' => $send_integral,
                        'type' => 1,
                        'order_id' => $id,
                        'create_time' => time()
                    ];
                    Db::name('integral_log')->insert($integral_data);

                    $msg_data = [
                        'user_id' => $info['user_id'],
                        'shop_id' => $info['shop_id'],
                        'order_id' => $id,
                        'title' => '购买商品赠送积分',
                        'content' => '购买商品赠送积分',
                        'create_time' => time()
                    ];
                    Db::name('msg')->insert($msg_data);

                    $custom_info = Db::name('customer')->where(['user_id' => $info['user_id'], 'shop_id' => $info['shop_id']])->find();
                    $custom_data = [
                        'success_order_count' => $custom_info['success_order_count'] + 1,
                        'integral' => $custom_info['integral'] + $send_integral,
                        'update_time' => time()
                    ];
                    Db::name('customer')->where(['user_id' => $info['user_id'], 'shop_id' => $info['shop_id']])->update($custom_data);
                }

                // 订单抽奖表对应记录修改为可抽奖
                Db::name('order_lottery')->where(['order_id' => $id])->update(['status' => 1]);

                Db::commit();
                apiReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '操作失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 获取评价页面订单商品信息
     * */
    public function getOrderGoodsList()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $goods_list = Db::name('vice_order')->where(['order_id' => $id])->select();
        if ($goods_list) {
            foreach ($goods_list as &$v) {
                $v['img'] = $v['img'] ? getPicture($v['img']) : getGoodsImg($v['goods_id']);
                $v['all_price'] = $v['price'] * $v['count'];

                if ($sku_list = getSkuName(explode('-', $v['sku_id']))) $v['sku'] = implode('，', array_column($sku_list, 'name'));
            }
            apiReturn(1, '获取数据成功', $goods_list);
        } else {
            apiReturn(2, '未查询到商品信息');
        }
    }

    /**
     * 商品评价
     * */
    public function goodsComment()
    {
        $input = Request()->param();

        $comment_list = json_decode($input['comment_list'], true);

        Db::startTrans();
        try {
            $time = time();
            if ($comment_list) {
                $have_empty = false;
                $data = [];
                foreach ($comment_list as &$v) {
                    if (empty($v['content'])) {
                        $have_empty = true;
                        break;
                    } else {
                        checkContent($v['content']);

                        $data[] = [
                            'user_id' => $v['user_id'],
                            'order_id' => $v['order_id'],
                            'vice_order_id' => $v['vice_order_id'],
                            'goods_id' => $v['goods_id'],
                            'star' => $v['star'],
                            'content' => $v['content'],
                            'imgs' => $v['imgs_id'],
                            'create_time' => $time
                        ];
                    }
                }

                if ($have_empty) apiReturn(2, '请针对所有商品作出评价');

                Db::name('goods_comment')->insertAll($data);

                $order_id = Db::name('vice_order')->where(['id' => $comment_list[0]['vice_order_id']])->value('order_id');
                $order_data = [
                    'status' => 5,
                    'update_time' => $time
                ];
                Db::name('order')->where(['id' => $order_id])->update($order_data);

                Db::commit();
                apiReturn(1, '评价成功');
            } else {
                Db::rollback();
                apiReturn(2, '评价数据出错，请稍后再试~');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 订单列表立即支付
     * */
    public function payNow()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        // 检查商品库存
        $goods_list = Db::name('vice_order')
            ->field('goods_id, SUM(count) as count')
            ->where(['order_id' => $id])
            ->group('goods_id')
            ->select();

        // 哪些商品库存不足记录下来
        $goods_name_arr = [];
        if ($goods_list) {
            foreach ($goods_list as &$v) {
                $check = $this->checkStock($v['goods_id'], $v['count']);
                if (!$check) $goods_name_arr[] = getGoodsName($v['goods_id']);
            }
        }
        if ($goods_name_arr) apiReturn(2, implode('，', $goods_name_arr) . '库存不足，请修改购买数量后重新下单');

        Db::startTrans();
        try {
            $info = Db::name('order')->where(['id' => $id, 'is_del' => 0])->find();
            if ($info) {
                $pay_order_sn = createOrderSn();
                Db::name('order')->where(['id' => $id])->setField('pay_order_sn', $pay_order_sn);

                $openid = Db::name("user")->where(['id' => $info['user_id']])->value("openid");

                Loader::import('wxsdk\wxPay', EXTEND_PATH);
                $obj = new \wxPay();
                //调用示例（最后两个参数为可选参数）
                $pay_price = C('TEST_PAY') ? 0.01 : $info['pay_price'];
                $pay_data = $obj->jsApi($openid, $pay_price, $pay_order_sn, '商品支付', getHost() . '/Index/Notify/notice');
                file_put_contents(RUNTIME_PATH . 'pay_data.txt', json_encode($pay_data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);

                if ($pay_data) {
                    $data = [
                        'order_sn' => $pay_order_sn,
                        'pay_data' => $pay_data
                    ];
                    Db::commit();
                    apiReturn(1, '获取支付信息成功', $data);
                } else {
                    Db::rollback();
                    apiReturn(2, '系统繁忙，请稍后再试~');
                }
            } else {
                Db::rollback();
                apiReturn(2, '订单不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 取消订单
     * */
    public function cancelOrder()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id, 'is_del' => 0])->find();
        if ($info) {
            Db::startTrans();
            try {
                if($info['status'] == 10 && $info['is_pay'] == 1 && $info['pay_type'] == 1){
                    // 堂食订单微信支付成功的订单取消订单，需要退款到微信
                    Loader::import('wxsdk\wxPay', EXTEND_PATH);
                    $obj = new \wxPay();

                    $price = C('TEST_PAY') ? 0.01 : $info['pay_price'];
                    $obj->refund($price, $price, $info['pay_order_sn'], $info['pay_order_sn'], '取消堂食订单退款');
                }

                $data = [
                    'status' => 8,
                    'update_time' => time()
                ];
                Db::name('order')->where(['id' => $id])->update($data);

                $time = time();
                if ($use_integral = $info['use_integral']) {
                    // 取消订单，兑换商品的积分返还【这个时候的订单还是未支付状态】
                    $integral_data = [
                        'user_id' => $info['user_id'],
                        'shop_id' => $info['shop_id'],
                        'integral' => $use_integral,
                        'type' => 5,
                        'order_id' => $id,
                        'create_time' => $time
                    ];
                    Db::name('integral_log')->insert($integral_data);

                    Db::name('customer')->where(['user_id' => $info['user_id'], 'shop_id' => $info['shop_id']])->setInc('integral', $use_integral);
                }

                if ($user_coupon_id = $info['user_coupon_id']) {
                    // 修改优惠券为待使用状态
                    Db::name('user_coupon')->where(['id' => $user_coupon_id])->update(['status' => 1, 'update_time' => $time]);
                }

                if ($lottery_coupon_id = $info['lottery_coupon_id']) {
                    // 修改优惠券为待使用状态
                    Db::name('user_lottery_coupon')->where(['id' => $lottery_coupon_id])->update(['is_use' => 0, 'update_time' => $time]);
                }

                Db::commit();
                apiReturn(1, '订单取消成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '订单取消失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 平台取消订单
     * */
    public function platformCancelOrder()
    {
        $input = Request()->param();

        $id = $input['id'];
        $cancel_reason = $input['cancel_reason'] ? : '超出配送距离';

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id, 'is_del' => 0])->find();
        if ($info) {
            Db::startTrans();
            try {
                $data = [
                    'status' => 8,
                    'cancel_reason' => $cancel_reason,
                    'update_time' => time()
                ];
                Db::name('order')->where(['id' => $id])->update($data);

                $time = time();

                // 使用积分原路退回
                if ($use_integral = $info['use_integral']) {
                    $integral_data = [
                        'user_id' => $info['user_id'],
                        'shop_id' => $info['shop_id'],
                        'integral' => $use_integral,
                        'type' => 5,
                        'order_id' => $id,
                        'create_time' => $time
                    ];
                    Db::name('integral_log')->insert($integral_data);

                    Db::name('customer')->where(['user_id' => $info['user_id'], 'shop_id' => $info['shop_id']])->setInc('integral', $use_integral);
                }

                // 修改优惠券为待使用状态
                if ($user_coupon_id = $info['user_coupon_id']) {
                    Db::name('user_coupon')->where(['id' => $user_coupon_id])->update(['status' => 1, 'update_time' => $time]);
                }

                // 付款金额原路退回
                $price = $info['pay_price'];
                if ($price > 0) {
                    Loader::import('wxsdk\wxPay', EXTEND_PATH);
                    $obj = new \wxPay();
                    $price = C('TEST_PAY') ? 0.01 : $price;
                    $obj->refund($price, $price, $info['pay_order_sn'], $info['pay_order_sn'], $cancel_reason);
                }

                // 发送站内消息
                $msg_data = [
                    'user_id' => $info['user_id'],
                    'shop_id' => $info['shop_id'],
                    'order_id' => $id,
                    'title' => '取消订单',
                    'content' => '您有一笔订单已被平台取消，原因：' . $cancel_reason,
                    'create_time' => time()
                ];
                Db::name('msg')->insert($msg_data);

                Db::commit();
                apiReturn(1, '订单取消成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '订单取消失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }


    /**
     * 取消套餐订单
     * */
    public function cancelMealOrder()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id, 'is_del' => 0])->find();
        if ($info) {
            $data = [
                'update_time' => time()
            ];
            $res = Db::name('order')->where(['id' => $id])->update($data);
            if ($res) {
                apiReturn(1, '订单取消成功');
            } else {
                apiReturn(2, '订单取消失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 删除订单
     * */
    public function delOrder()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id, 'is_del' => 0])->find();
        if ($info) {
            $res = Db::name('order')->where(['id' => $id])->setField('is_del', 1);
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }


    /**
     * 申请售后页面数据
     */
    public function afterData()
    {
        $after_reason = C('AFTER_REASON');

        $data = [
            'after_reason' => array_values(array_filter($after_reason))
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 申请售后
     */
    public function applyAfter()
    {
        $input = Request()->param();

        $id = $input['id'];
        //        $after_type = $input['after_type'];
        $after_reason = $input['after_reason'];
        $after_desc = $input['after_desc'];

        if (empty($id)) apiReturn(2, '订单ID不存在');
        //        if (empty($after_type)) apiReturn(2, '请选择申请类型');
        if (empty($after_reason)) apiReturn(2, '请选择原因');
        if (empty($after_desc)) apiReturn(2, '请填写说明描述');

        $info = Db::name('order')->where(['id' => $id])->find();
        if (empty($info)) apiReturn(2, '订单不存在或已删除');

        $data = [
            'status' => 6,
            //            'after_type' => $after_type,
            'after_status' => 1,
            'after_reason' => $after_reason,
            'after_desc' => $after_desc,
            'update_time' => time()
        ];

        $res = Db::name('order')->where(['id' => $id])->update($data);
        if ($res) {
            $order_sn = $info['order_sn'];
            $time = timeFormat(time());
            $use_integral = $info['use_integral'];
            $pay_price = $info['pay_price'];

            $content = "<C><B>退单通知</B></C><BR>
订单编号：${order_sn}<BR>
退单时间：${time}<BR>
退单原因：${after_reason}<BR>
说明描述：${after_desc}<BR>
退单积分：${use_integral}<BR>
退单金额：${pay_price}元<BR>
<AUDIO-REFUND><BR>
";
            // 打印订单
            $printer_sn = Db::name('shop')->where(['id' => $info['shop_id']])->value('printer_sn');
            if ($content && $printer_sn) {
                Loader::import('printer/Api', EXTEND_PATH);
                $obj = new \Api(C('PRINTER_APPID'), C('PRINTER_APPSECRET'));
                $obj->prints($printer_sn, $content);
            }

            apiReturn(1, '申请成功');
        } else {
            apiReturn(2, '申请失败');
        }
    }

    /**
     * 套餐订单列表
     * */
    public function mealOrderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        $where['is_del'] = 0;

        $list = Db::name('order')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {

                $vice_order_info = Db::name('vice_order')->where(['order_id' => $v['id']])->find();
                if ($vice_order_info) {
                    $v['name'] = $vice_order_info['name'];
                    $v['img'] = getPicture($vice_order_info['img']);

                    $meal_other_info = json_decode($vice_order_info['meal_other_info_json'], true);
                    $v['main_goods_name'] = $meal_other_info['main_goods_name'];
                    $v['main_goods_count'] = $meal_other_info['main_goods_count'] * $vice_order_info['count'];

                    // 进度条
                    /*$all_plan_count = Db::name('vice_order_plan')->where(['order_id' => $v['id']])->count();
                    $send_plan_count = Db::name('vice_order_plan')->where(['order_id' => $v['id'], 'status' => 1])->count();
                    $progress = intval(($send_plan_count / $all_plan_count) * 100);
                    $v['progress'] = $progress;*/
                    // 进度条
                    $main_valid_day = $meal_other_info['valid_day']; // 主产品成长期
                    $start_time = $v['pay_time'] ? timeFormat($v['pay_time'], 'Y-m-d') : 0;
                    $end_time = date('Y-m-d');
                    if ($start_time) {
                        $days = getDays($start_time, $end_time);
                        $progress = intval(($days / $main_valid_day) * 100);
                        $v['progress'] = $progress;
                    } else {
                        $v['progress'] = 0;
                    }
                }
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 套餐订单详情
     * */
    public function mealOrderDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id])->find();
        if ($info) {
            $info['create_time'] = timeFormat($info['create_time']);

            $vice_order_info = Db::name('vice_order')->where(['order_id' => $id])->find();
            $info['meal_id'] = $vice_order_info['meal_id'];
            $info['img'] = getPicture($vice_order_info['img']);
            $info['name'] = $vice_order_info['name'];
            $info['price'] = $vice_order_info['price'];
            $info['count'] = $vice_order_info['count'];

            $meal_other_info = json_decode($vice_order_info['meal_other_info_json'], true);
            $meal_other_info['main_goods_count'] = $meal_other_info['main_goods_count'] * $vice_order_info['count'];
            $meal_other_info['minor_goods_count'] = $meal_other_info['minor_goods_count'] * $vice_order_info['count'];
            $info['meal_other_info'] = $meal_other_info;

            $plan_list = Db::name('vice_order_plan')->where(['order_id' => $id])->order('send_date asc, is_main asc')->select();
            // 已赠送数量
            $send_count = 0;
            if ($plan_list) {
                foreach ($plan_list as &$v) {
                    if ($v['status'] == 1) $send_count += $v['count'];
                }
            }
            $info['plan_list'] = $plan_list ? : [];
            $info['send_count'] = $send_count;

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 信息设置回显数据
     * */
    public function userInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $user_info = Db::name('user')->field('id,avatar,username,mobile')->where(['id' => $user_id])->find();
        if ($user_info) {
            $user_info['avatar_path'] = doAvatar($user_info['avatar']);
            $user_info['hide_mobile'] = hideMobile($user_info['mobile']);

            apiReturn(1, '获取数据成功', $user_info);
        } else {
            apiReturn(2, '用户信息不存在或已禁用');
        }
    }

    /**
     * 保存用户信息
     * */
    public function saveUserInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $avatar = $input['avatar'];
        $username = $input['username'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($username)) apiReturn(2, '请输入昵称');

        Db::startTrans();
        try {
            $info = Db::name('user')->where(['id' => $user_id])->find();

            if ($info) {
                $data = [
                    'avatar' => $avatar,
                    'username' => $username,
                    'update_time' => time()
                ];

                Db::name('user')->where(['id' => $user_id])->update($data);

                Db::commit();
                apiReturn(1, '保存成功');
            } else {
                Db::rollback();
                apiReturn(2, '用户不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 我的券包
     * */
    public function couponList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $shop_id = $input['shop_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $status = $input['status'] ? : 0;// 0：待领取，1：待使用，2：已过期
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($shop_id)) apiReturn(2, '门店ID缺失');

        $where['user_id'] = $user_id;
        $where['shop_id'] = $shop_id;
        $where['is_del'] = 0;

        if ($status == 0) {
            // 待领取
            $user_coupon_list = Db::name('user_coupon')->field('coupon_id')->where($where)->select();
            $coupon_ids = array_column($user_coupon_list, 'coupon_id');

            $map['shop_id'] = $shop_id;
            if ($coupon_ids) $map['id'] = ['NOT IN', $coupon_ids];
            $list = Db::name('coupon')->where($map)->order('id desc')->page($page, $pagesize)->select();
        } elseif ($status == 1) {
            // 待使用
            $where['status'] = 1;
            $where['expire_time'] = ['egt', date('Y-m-d')];
            $list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price,expire_time,status,create_time')->where($where)->order('id desc')->page($page, $pagesize)->select();
        } else {
            // 已过期
            $where['expire_time'] = ['lt', date('Y-m-d')];
            $list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price,expire_time,status,create_time')->where($where)->order('id desc')->page($page, $pagesize)->select();
        }

        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 领取优惠券
     * */
    public function getCoupon()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $shop_id = $input['shop_id'];
        $coupon_id = $input['coupon_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($shop_id)) apiReturn(2, '门店ID缺失');
        if (empty($coupon_id)) apiReturn(2, '优惠券ID缺失');

        $info = Db::name('coupon')->where(['id' => $coupon_id])->find();
        if ($info) {
            $data = [
                'user_id' => $user_id,
                'shop_id' => $shop_id,
                'coupon_id' => $coupon_id,
                'coupon_name' => $info['name'],
                'full_price' => $info['full_price'],
                'face_price' => $info['face_price'],
                'expire_time' => date('Y-m-d', strtotime("+" . $info['use_day'] . " day")),
                'create_time' => time()
            ];
            $res = Db::name('user_coupon')->insert($data);
            if ($res) {
                apiReturn(1, '领取成功');
            } else {
                apiReturn(2, '领取失败');
            }
        } else {
            apiReturn(2, '优惠券不存在或已删除');
        }
    }

    /**
     * 实物券列表
     * */
    public function lotteryCouponList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $shop_id = $input['shop_id'];
        $is_use = $input['is_use'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 15;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($shop_id)) apiReturn(2, '门店ID缺失');

        $where = [
            'user_id' => $user_id,
            'shop_id' => $shop_id,
            'is_use' => $is_use
        ];

        $list = Db::name('user_lottery_coupon')->field('id,coupon_img,coupon_name,update_time,create_time')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['coupon_img'] = getPicture($v['coupon_img']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d H:i');
                $v['update_time'] = timeFormat($v['update_time'], 'Y-m-d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 积分明细
     * */
    public function integralList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $shop_id = $input['shop_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $integral = Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->value('integral');

        $list = Db::name('integral_log')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['type_desc'] = doIntegralType($v['type']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }
        }

        $data = [
            'integral' => $integral,
            'list' => $list ? : []
        ];
        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 钱包明细
     * */
    public function balanceList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $balance = Db::name('user')->where(['id' => $user_id])->value('balance');

        $list = Db::name('balance_log')->where(['user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['type_desc'] = doBalanceType($v['type']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }
        }

        $data = [
            'balance' => sprintf('%.2f', $balance),
            'list' => $list ? : []
        ];
        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 我的收藏
     * */
    public function collectList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('collect c')
            ->join('xindu_goods g', 'c.to_id = g.id', 'left')
            ->field('g.id,g.img,g.name,g.min_price,g.min_vip_price')
            ->where(['user_id' => $user_id, 'type' => 1, 'status' => 1])
            ->page($page, $pagesize)
            ->select();

        if ($list) {
            $user_level = Db::name('user')->where(['id' => $user_id])->value('level');

            foreach ($list as &$v) {
                $price = $user_level > 1 ? $v['min_vip_price'] : $v['min_price'];
                $v['price'] = sprintf('%.2f', $price);
                $v['img'] = getPicture($v['img']);
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 我的分享
     * */
    public function getShareData()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        //分享二维码
        $qr = Db::name('user')->where(['id' => $user_id])->value('qr');
        if (!$qr) {
            $qr = createUserQr($user_id);
        }
        $qr = getPicture($qr);

        // 顾客总数：形成上下级关系
        $bind_user_count = Db::name('user')->where(['up_user_id' => $user_id])->count();

        // 成功分享：已激活的总数
        $success_user_count = Db::name('user')->where(['up_user_id' => $user_id])->count();

        // 今日新增
        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d')) + 24 * 3600 - 1;
        $today_bind_user_count = Db::name('user')->where(['up_user_id' => $user_id, 'create_time' => ['between', [$start_time, $end_time]]])->count();

        $data = [
            'qr' => $qr,
            'bind_user_count' => $bind_user_count,
            'success_user_count' => $success_user_count,
            'today_bind_user_count' => $today_bind_user_count,
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 意见反馈
     * */
    public function addFeedback()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $content = $input['content'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($content)) apiReturn(2, '请输入反馈意见');

        checkContent($content);

        $data = [
            'user_id' => $user_id,
            'content' => $content,
            'create_time' => time()
        ];

        $res = Db::name('feedback')->insert($data);
        if ($res) {
            apiReturn(1, '反馈成功');
        } else {
            apiReturn(2, '反馈失败');
        }
    }

    /**
     * 关于我们
     * */
    public
    function aboutUs()
    {
        $content = Db::name('about_us')->where(['id' => 1])->value('content');

        $content = doEditorContent($content);

        apiReturn(1, '获取数据成功', $content);
    }

    /**
     * 门店列表
     * */
    public function shopList()
    {
        $input = Request()->param();

        $lat = $input['lat'];
        $lng = $input['lng'];

        if (empty($lat) || empty($lng)) {
            $list = Db::name('shop')->where(['is_del' => 0])->select();
        } else {
            $sql = 'select *, ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lng . '*PI()/180-lng*PI()/180)/2),2)))*1000) AS juli from cater_shop where is_del = 0 order by juli asc ';
            $list = Db::name('shop')->query($sql);
        }

        if ($list) {
            if ($list) {
                foreach ($list as &$v) {
                    $v['juli'] = $v['juli'] > 1000 ? (intval($v['juli']) / 1000) . 'km' : intval($v['juli']) . 'm';
                }
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 注册门店客户数据
     * */
    public function registerCustomer()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $shop_id = $input['shop_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($shop_id)) apiReturn(2, '门店ID缺失');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if ($user_info) {
            $count = Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->count();
            if ($count) {
                apiReturn(1, '注册门店客户成功');
            } else {
                $customer_data = [
                    'user_id' => $user_id,
                    'shop_id' => $shop_id,
                    'create_time' => time()
                ];

                $res = Db::name('customer')->insert($customer_data);
                if ($res) {
                    apiReturn(1, '注册门店客户成功');
                } else {
                    apiReturn(2, '注册门店客户失败');
                }
            }
        } else {
            apiReturn(2, '用户数据存在或已删除');
        }


    }


    /**
     * 用户余额
     * */
    public function userBalance()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $balance = Db::name('user')->where(['id' => $user_id])->value('balance');

        apiReturn(1, '获取数据成功', $balance);
    }

    /**
     * 我的分享数据
     * */
    public function userShareInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('user')->field('id,qr,code,up_user_id')->where(['id' => $user_id])->find();
        if ($info) {
            $info['qr'] = getPicture($info['qr']);
            $info['all_share_count'] = Db::name('user')->where(['up_user_id' => $user_id])->count();
            $up_username = Db::name('user')->where(['id' => $info['up_user_id']])->value('username');
            $info['up_username'] = $up_username ? : '';

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '用户不存在或已删除');
        }
    }

    /**
     * 分享用户列表
     * */
    public function shareUserList()
    {

        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('user')->where(['up_user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = doAvatar($v['avatar']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 业绩统计汇总
     * */
    public function census()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $shop_id = $input['shop_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $shop_ids = getUserAuthShop($user_id);
        if (empty($shop_ids)) apiReturn(2, '您暂无查看门店业绩权限');

        $start_time = strtotime(date('Y-m-d'));
        $end_time = $start_time + 24 * 3600 - 1;
        if (!empty($start_time) && empty($end_time)) {
            $today_where["create_time"] = ["egt", $start_time];
        } elseif (empty($start_time) && !empty($end_time)) {
            $today_where["create_time"] = ["elt", $end_time];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $today_where["create_time"] = ['between', [$start_time, $end_time]];
        }

        if ($shop_id) {
            $where['shop_id'] = $shop_id;
        } else {
            $where['shop_id'] = ['IN', $shop_ids];
        }

        $price_where = ['is_pay' => 1, 'status' => ['neq', 7], 'after_type' => ['neq', '退货退款']];

        // 今日订单数
        $today_order_count = Db::name('order')->where($where)->where($today_where)->count();

        // 总订单数
        $all_order_count = Db::name('order')->where($where)->count();

        // 今日订单总额
        $today_order_price = Db::name('order')->where($where)->where($today_where)->where($price_where)->sum('pay_price');

        // 总订单总额
        $all_order_price = Db::name('order')->where($where)->where($price_where)->sum('pay_price');

        $empty_shop = [
            [
                'id' => 0,
                'name' => '请选择门店'
            ]
        ];
        $shop_list = Db::name('shop')->field('id,name')->where(['id' => ['IN', $shop_ids], 'is_del' => 0])->select();

        $data = [
            'shop_list' => $shop_list ? array_merge($empty_shop, $shop_list) : $empty_shop,
            'today_order_count' => $today_order_count,
            'all_order_count' => $all_order_count,
            'today_order_price' => sprintf('%.2f', $today_order_price),
            'all_order_price' => sprintf('%.2f', $all_order_price)
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 业绩统计列表
     * */
    public function censusOrderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $shop_id = $input['shop_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $shop_ids = getUserAuthShop($user_id);
        if (empty($shop_ids)) apiReturn(2, '您暂无查看门店业绩权限');

        if ($shop_id) {
            $where['shop_id'] = $shop_id;
        } else {
            $where['shop_id'] = ['IN', $shop_ids];
        }

        $price_where = ['is_pay' => 1, 'status' => ['neq', 7], 'after_type' => ['neq', '退货退款']];

        $list = Db::name('order')->field('id,order_sn,pay_price')->where($where)->where($price_where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['count'] = Db::name('vice_order')->where(['order_id' => $v['id']])->sum('count');
                $v['pay_price'] = sprintf('%.2f', $v['pay_price']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 幸运大转盘页面数据
     * */
    public function lotteryData()
    {
        $input = Request()->param();

        $order_id = $input['order_id'];

        if (empty($order_id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order_lottery')->where(['order_id' => $order_id])->find();

        if (empty($info)) apiReturn(2, '未查询到该订单抽奖数据');
        if ($info['status'] != 1) apiReturn(2, '该订单抽奖状态不可用');

        $lottery_coupon_ids = Db::name('activity')->where(['id' => $info['activity_id']])->value('lottery_coupon_ids');
        if (empty($lottery_coupon_ids)) apiReturn(2, '抽奖奖励缺失');

        $lottery_coupon_list = Db::name('lottery_coupon')->where(['id' => ['IN', $lottery_coupon_ids]])->select();
        if ($lottery_coupon_list) {
            foreach ($lottery_coupon_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
        } else {
            apiReturn(2, '抽奖奖励缺失');
        }
        $info['activity_info']['coupon_name'] = $lottery_coupon_list;

        // 中奖数据
        $user_lottery_coupon_list = Db::name('user_lottery_coupon')->field('coupon_name,coupon_img,create_time')->where(['order_lottery_id' => $info['id']])->order('id asc')->select();
        if ($user_lottery_coupon_list) {
            foreach ($user_lottery_coupon_list as &$v) {
                $v['coupon_img'] = getPicture($v['coupon_img']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d H:i');
            }
        }

        $data = [
            'info' => $info,
            'user_lottery_coupon_list' => $user_lottery_coupon_list ? : [],
            'lottery_rule' => explode(PHP_EOL, C('LOTTERY_RULE'))
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 幸运大转盘中奖
     * */
    public function lottery()
    {
        $input = Request()->param();

        $id = $input['id'];// order_lottery表主键id

        if (empty($id)) apiReturn(2, '订单抽奖ID缺失');

        $info = Db::name('order_lottery ol')->join('cater_activity a', 'ol.activity_id = a.id', 'left')->field('ol.user_id,ol.shop_id,ol.order_id,a.lottery_coupon_ids')->where(['ol.id' => $id])->find();
        if ($info || $info['lottery_coupon_ids']) {
            $lottery_coupon_list = Db::name('lottery_coupon')->field('id,img,name,goods_id,count')->where(['id' => ['IN', $info['lottery_coupon_ids']]])->select();
            $coupon_name_list = []; // 可参与抽奖的实物券集合
            if ($lottery_coupon_list) {
                foreach ($lottery_coupon_list as &$v) {
                    if ($v['count'] > 0) {
                        $coupon_name_list[] = $v['name'];
                    }
                }
            }
            $name_index = array_rand($coupon_name_list);
            $lottery_coupon_name = $coupon_name_list[$name_index];// 抽取到的实物券名称

            // 通过实物券名称找出中奖下标
            $index = array_search($lottery_coupon_name, array_column($lottery_coupon_list, 'name'));
            $lottery_coupon = $lottery_coupon_list[$index];

            $can_count = Db::name('order_lottery')->where(['id' => $id])->value('can_count');
            if($can_count <= 0) apiReturn(2,'抽奖次数已用完');

            Db::startTrans();
            try {
                Db::name('order_lottery')->where(['id' => $id])->setDec('can_count', 1);

                $time = time();

                $coupon_name = $lottery_coupon['name'];
                $coupon_img = getPicture($lottery_coupon['img']);

                $data = [
                    'order_lottery_id' => $id,
                    'user_id' => $info['user_id'],
                    'shop_id' => $info['shop_id'],
                    'goods_id' => $lottery_coupon['goods_id'],
                    'coupon_name' => $coupon_name,
                    'coupon_img' => str_replace(getHost(), '', $coupon_img),
                    'is_use' => 0,
                    'create_time' => $time
                ];

                Db::name('user_lottery_coupon')->insert($data);

                Db::name('lottery_coupon')->where(['id' => $lottery_coupon_list[$index]['id']])->setDec('count', 1);

                $data = [
                    'index' => $index,
                    'coupon_img' => $coupon_img,
                    'coupon_name' => $coupon_name,
                    'create_time' => timeFormat($time, 'Y-m-d H:i')
                ];

                Db::commit();
                apiReturn(1, '抽奖成功', $data);
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '抽奖失败');
            }


        } else {
            apiReturn(2, '抽奖信息不存在');
        }
    }


    /**
     * 幸运大转盘中奖
     * */
    public function lotteryBak()
    {
        $input = Request()->param();

        $id = $input['id'];                       // order_lottery表主键id
        $coupon = $input['coupon'];               // 实物券名称
        $coupon_img = $input['coupon_img'] ? : '';// 实物券名称

        if (empty($id)) apiReturn(2, '订单抽奖ID缺失');
        if (empty($coupon)) apiReturn(2, '实物券缺失');

        $info = Db::name('order_lottery')->where(['id' => $id])->find();
        if (empty($info)) apiReturn(2, '未查询到该订单抽奖数据');
        if ($info['status'] != 1) apiReturn(2, '该订单抽奖状态不可用');
        if ($info['can_count'] <= 0) apiReturn(2, '该订单抽奖次数已用完');

        try {
            Db::name('order_lottery')->where(['id' => $id])->setDec('can_count', 1);

            $time = time();

            $data = [
                'order_lottery_id' => $id,
                'user_id' => $info['user_id'],
                'shop_id' => $info['shop_id'],
                'coupon_name' => $coupon,
                'coupon_img' => str_replace(getHost(), '', $coupon_img),
                'is_use' => 0,
                'create_time' => $time
            ];

            Db::name('user_lottery_coupon')->insert($data);

            $data = [
                'coupon_img' => $coupon_img,
                'coupon_name' => $coupon,
                'create_time' => timeFormat($time, 'Y-m-d H:i')
            ];

            Db::commit();
            apiReturn(1, '抽奖成功', $data);
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '抽奖失败');
        }
    }
}
